import random

from django.http.response import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.views import APIView

from . import constants
from meiduo.libs.captcha.captcha import Captcha
from rest_framework.generics import GenericAPIView

from . import constants,serializers
from meiduo.libs.yuntongxun.sms import CCP
from rest_framework.response import Response
from celery_tasks.sms.tasks import send_sms_code

class ImgCodeAPIView(APIView):
    def get(self,request,image_code_id):
        captcha = Captcha()
        text,image = captcha.generate_captcha()
        redis = get_redis_connection('verify')
        redis.setex('img_%s'%image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        return HttpResponse(image,content_type='images/jpg')

def index(request):
    return HttpResponse('ok')


class SMSCodeAPIView(GenericAPIView):
    serializer_class = serializers.SMSCodeSerializer
    def get(self,request,mobile):
        serializers = self.get_serializer(data=request.query_params)
        serializers.is_valid(raise_exception=True)

        sms_code = '%06d'%random.randint(0,999999)
        print(sms_code)

        redis = get_redis_connection('verify')

        pl = redis.pipeline()
        pl.multi()
        pl.setex('sms_%s'%mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        pl.setex('send_flag_%s'%mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        pl.execute()

        send_sms_code.delay(mobile=mobile,sms_code=sms_code)

        # ccp = CCP()
        # sms_expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        #
        # try:
        #     ccp.send_template_sms(mobile,[sms_code,sms_expires],1)
        # except:
        #     return Response({'message':'发送短信失败!'},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        return Response({'message':'发送短信成功'},status=status.HTTP_200_OK)
